import { createReducer } from './util';
import * as DevTeamAction from '../actions/dev-team';
import _ from 'lodash';

export const currentUserDevTeamList = createReducer(on => {
  on(DevTeamAction.listByCurrentUser);
}, []);

export const devTeamDetail = createReducer(on => {
  on(DevTeamAction.getDetail);
  on(DevTeamAction.setLeader)
    .completed((state, action) => {
      const { userId, enable } = action.payload;
      const members = state.members.map(member => {
        if (member.id === userId) {
          return Object.assign({}, member, { leader: enable });
        }
        return member;
      });
      return Object.assign({}, state, { members });
    });
  on(DevTeamAction.addMembers)
    .completed((state, action) => {
      const oldMemberIds = state.members.map(member => member.id);
      const newMembers = action.payload.filter(member => !_.includes(oldMemberIds, member.id));
      const members = _.concat(state.members, newMembers);
      return Object.assign({}, state, { members });
    });
  on(DevTeamAction.removeMember)
    .completed((state, action) => {
      const userId = action.payload;
      const members = _.filter(state.members, member => member.id !== userId);
      return Object.assign({}, state, { members });
    });
  on(DevTeamAction.update)
    .completed((state, action) => {
      const { name, desc } = action.payload;
      const devTeam = Object.assign({}, state.devTeam, { name, desc });
      return Object.assign({}, state, { devTeam });
    });
}, {});

export const suggestDevTeam = createReducer(on => {
  on(DevTeamAction.suggest);
}, []);

export const devTeamList = createReducer(on => {
  on(DevTeamAction.search);
}, {
  currentPage: 0,
  total: 0,
  list: []
});

export const managedDevTeam = createReducer(on => {
  on(DevTeamAction.managedDevTeam);
}, []);
